/* 
   icar is Copyright (c) 2015 Zheng

   Time: 2015-04-13 09:38
   Author: Zheng Chao
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <syslog.h>
#include <stdarg.h>
#include <errno.h>
#include <time.h>

#include "icar.h"
#include "icar_log.h"

int debuglevel = DEFAULT_LEVEL;

int idaemon = 1;


void icar_die(char *message)
{
	openlog(progname, LOG_PID, 0);

	syslog(LOG_CRIT, "FATAL ERROR: [%s] [%s]\n", message, strerror(errno));
	closelog();
	exit(-1);
}

void _icar_debug(const char *filename, int lineno, const char *fmt)
{
	openlog(progname, LOG_PID, 0);
	syslog(LOG_ERR, "(%s:%d): [%s] [%s]", filename, lineno, fmt, strerror(errno));
	closelog();
}

void _icar_daemon(int level, const char *filename, int lineno, const char *fmt, ...)
{
	char buf[28];
	char log[1024];
	va_list ap;
	time_t ts;

	time(&ts);

	if (debuglevel >= level) {
		if (idaemon) {
			int n = 0;
			n = snprintf(log, sizeof(log), "%.24s %s[%u](%s:%d): ",
					ctime_r(&ts, buf), progname, getpid(), filename, lineno);
			openlog(progname, LOG_PID, 0);
			va_start(ap, fmt);
			n += vsnprintf(log+n, sizeof(log) - n, fmt, ap);
			va_end(ap);
			syslog(level, "%s\n", log);
			closelog();
		} else {
			if (level <= LOG_WARNING) {
				fprintf(stderr, "%.24s %s[%u](%s:%d): ",
						ctime_r(&ts, buf), progname, getpid(), filename, lineno);
				va_start(ap, fmt);
				vfprintf(stderr, fmt, ap);
				va_end(ap);
				fputc('\n', stderr);
			} else if (!idaemon) {
				fprintf(stdout, "%.24s %s[%u](%s:%d): ",
						ctime_r(&ts, buf), progname, getpid(), filename, lineno);
				va_start(ap, fmt);
				vfprintf(stdout, fmt, ap);
				va_end(ap);
				fputc('\n', stdout);
				fflush(stdout);
			}
		}
	}
}
